﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Tapper
{
    public class Character : Entity //: Movable
    {
        public readonly Texture2D m_texture;
        public Vector2 m_pos           = new Vector2(300.0f, 240.0f);
        internal Vector2 m_vel         = new Vector2(0, 0);
        protected float m_accel        = 500.0f;
        protected float m_maxvel       = 100.0f;
        protected float m_scale        = 1.0f;
        
        protected Character(World world, Texture2D texture, Vector2 pos, Vector2 vel)
            : base(world)
        {
            m_texture = texture;
            m_pos     = pos;
            m_vel     = vel;          
        }

        protected virtual Vector2 GetPosX() { return Vector2.Zero; }

        protected virtual float GetPosY() { return m_pos.Y; }

        public override void Update(GameTime gametime)
        {
            var moveDir = GetPosX();
            var movePosY = GetPosY();
            var deltaTime = (float)gametime.ElapsedGameTime.TotalSeconds;

            if (moveDir.Length() > 0.0f)
            {
                moveDir.Normalize();
                m_vel += moveDir * m_accel * deltaTime;
                if (m_vel.Length() > m_maxvel)
                {
                    m_vel.Normalize();
                    m_vel *= m_maxvel;
                }
            }
            else
            {
                const float friction = 5.0f;
                var mag = m_vel.Length();

                if (mag > 0.0f)
                {
                    m_vel.Normalize();
                    var mul = (mag - mag * friction * deltaTime);
                    m_vel = m_vel * mul;
                }
            }
            m_pos.Y = movePosY;
            m_pos += m_vel * deltaTime;

        }

        public virtual float LayerTexture() { return 0.1f; }

        public override void Draw(GameTime gametime, SpriteBatch spritebatch)
        {
            var vPlayerScale = new Vector2(m_scale, m_scale);
            var vPlayerSize  = new Vector2(m_texture.Width, m_texture.Height);

            spritebatch.Draw(m_texture, /*m_world.m_camera.TranformPos*/(m_pos), null, Color.White, 0.0f, vPlayerSize * 0.5f, /*m_world.m_camera.TranformScale*/(vPlayerScale), SpriteEffects.None, LayerTexture());
        }
    }
}